package com.tourlaid.mamagerment.service.impl

import com.tourlaid.mamagerment.entity.ShopGoods
import com.tourlaid.mamagerment.enums.TldExceptionEnum
import com.tourlaid.mamagerment.mapper.ShopGoodsMapper
import com.tourlaid.mamagerment.service.ShopGoodsService
import com.tourlaid.mamagerment.service.StockInService
import com.tourlaid.mamagerment.util.LoginUtil
import com.tourlaid.mamagerment.util.TldException
import org.springframework.stereotype.Service
import javax.annotation.Resource

/**
 * Created by xiaoyongge on 2017/8/1.
 */
@Service("shopGoodsService")
class ShopGoodsServiceImpl : ShopGoodsService {

    @Resource
    val shopGoodsMapper: ShopGoodsMapper? = null
    @Resource
    val stockInService: StockInService? = null

    override fun queryForList(): List<ShopGoods> {
        return shopGoodsMapper!!.queryForList();
    }

    override fun plusStock(shopId: Long?, stockInId: Long, stock: Int?) {
        val stockIn = stockInService!!.getById(stockInId)
        if (stockIn == null) throw TldException(TldExceptionEnum.STOCKIN_NULL)
        val shopGoods = shopGoodsMapper!!.getByShopIdAndGoodsId(shopId, stockIn.goodsId)
        if (shopGoods == null) {
            this.insert(shopId!!, stockIn.goodsId!!, stock!!)
            return
        }
        // 更新
        shopGoodsMapper!!.plusStock(shopGoods.id, stock, LoginUtil.userId);
    }

    override fun insert(shopId: Long, goodsId: Long, stock: Int) {
        var shopGoods = ShopGoods()
        shopGoods.shopId = shopId
        shopGoods.goodsId = goodsId
        shopGoods.stock = stock
        shopGoods.creator = LoginUtil.userId
        shopGoods.editor = LoginUtil.userId
        shopGoodsMapper!!.insert(shopGoods)
    }

    override fun minusStock(shopId: Long?, stockInId: Long, stock: Int?) {
        val stockIn = stockInService!!.getById(stockInId)
        if (stockIn == null) throw TldException(TldExceptionEnum.STOCKIN_NULL)
        val shopGoods = shopGoodsMapper!!.getByShopIdAndGoodsId(shopId, stockIn.goodsId)
        // 更新
        shopGoodsMapper!!.minusStock(shopGoods!!.id, stock, LoginUtil.userId);
    }
}